package model

import (
	"context"
	"gorm.io/gorm"
)

type (
	RoleGroup interface {
		Insert(ctx context.Context, roleId, groupId int) error
		BatchInsert(ctx context.Context, roleId int, groupIds []int) error
		FindByRoleId(ctx context.Context, roleId int) ([]*AuthxRoleGroup, error)
		FindByGroupIds(ctx context.Context, groupId int) ([]*AuthxRoleGroup, error)
		Delete(ctx context.Context, roleId, groupId int) error
		DeleteByRoleId(ctx context.Context, roleId int) error
	}

	defaultRoleGroup struct {
		db *gorm.DB
	}
)

func NewRoleGroup(db *gorm.DB) RoleGroup {
	return &defaultRoleGroup{
		db: db,
	}
}

func (d *defaultRoleGroup) model() *gorm.DB {
	return d.db.Model(&AuthxRoleGroup{})
}

func (d *defaultRoleGroup) Insert(ctx context.Context, roleId, groupId int) error {
	return d.db.Create(&AuthxRoleGroup{
		RoleId:  roleId,
		GroupId: groupId,
	}).Error
}

func (d *defaultRoleGroup) BatchInsert(ctx context.Context, roleId int, groupIds []int) error {
	var records []*AuthxRoleGroup
	for _, groupId := range groupIds {
		records = append(records, &AuthxRoleGroup{
			RoleId:  roleId,
			GroupId: groupId,
		})
	}
	d.model().Where("role_id = ?", roleId).Delete(&AuthxRoleGroup{})
	return d.db.Create(&records).Error
}

func (d *defaultRoleGroup) FindByRoleId(ctx context.Context, roleId int) ([]*AuthxRoleGroup, error) {
	var result []*AuthxRoleGroup
	if err := d.model().Where("role_id = ?", roleId).Find(&result).Error; err != nil {
		return nil, err
	}
	return result, nil
}

func (d *defaultRoleGroup) FindByGroupIds(ctx context.Context, groupId int) ([]*AuthxRoleGroup, error) {
	var result []*AuthxRoleGroup
	if err := d.model().Where("group_id = ?", groupId).Find(&result).Error; err != nil {
		return nil, err
	}
	return result, nil
}

func (d *defaultRoleGroup) Delete(ctx context.Context, roleId, groupId int) error {
	return d.model().
		Where("role_id = ? AND group_id = ?", roleId, groupId).
		Delete(&AuthxRoleGroup{}).Error
}

func (d *defaultRoleGroup) DeleteByRoleId(ctx context.Context, roleId int) error {
	return d.model().
		Where("role_id = ?", roleId).
		Delete(&AuthxRoleGroup{}).Error
}
